﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Windows.Forms;

namespace RegisterMain
{
    public partial class Form1 : Form
    {
        [DllImport("User32.dll", EntryPoint = "SendMessage")]

        private static extern int SendMessage(

        IntPtr hWnd, // handle to destination window    

        int Msg, // message    

        int wParam, // first message parameter    

        ref COPYDATASTRUCT lParam  // second message parameter     

        );

      
        [DllImport("user32.dll", EntryPoint = "FindWindow")]
        private extern static IntPtr FindWindow(string lpClassName, string lpWindowName);


        public struct COPYDATASTRUCT
        {

            public IntPtr dwData;

            public int cbData;

            [MarshalAs(UnmanagedType.LPStr)]
            public string lpData;

        }

        const int WM_COPYDATA = 0x004A;




        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
           
            ShareMem MemDB = new ShareMem();//声明共享内存操作类
            MemDB.Init("shared",   1024);//初始化共享内存   返回0表示初始化成功
            MemDB.Write_Str(textBox1.Text);
            
            return;

            if (txtpl.Text.Trim() != "")
            {
                int row = 0;//行
                int col = 0;//lie
                FileStream fs;
                fs = new FileStream(txtpl.Text.Trim(), FileMode.Open, FileAccess.Read);
                StreamReader sr;
                sr = new StreamReader(fs);
                List<string> arrary = new List<string>();
                List<string> arrary_Sec = new List<string>();
                while (!sr.EndOfStream)
                {
                    string[] arr = sr.ReadLine().Split(' ');
                    col = arr.Length;
                    string temp = "";
                    for (int x = 0; x < col; x++)
                    {
                        temp = Convert.ToString(arr[x]);
                    }
                    arrary.Add(temp);
                    //for (int y = 0; y < col; y++)
                    //{
                    //    Console.Write(arrary[row][y] + " ");
                    //}
                    row++;
                   // Console.WriteLine("\n");
                }
                sr.Close();
                fs.Close();
                if (arrary.Count > 0)
                {
                    string ss = "";
                    foreach (string s in arrary)
                    {
                        arrary_Sec.Add(s);
                      //  ss += "\n"+ s;
                    }
                    WriteLogFile(arrary_Sec);
                }
                else
                { MessageBox.Show("选择文件为空！"); }
            }
            else
            {
                if (textBox1.Text.Trim().Length < 10)
                {
                    MessageBox.Show("机器码不正确！"); return;
                }
                else
                    textBox2.Text = AuthorizeEncrypted(textBox1.Text.Trim());
            }
        }
        private string AuthorizeEncrypted(string origin)
        {
            // 此处使用了组件支持的DES对称加密技术
            return HslCommunication.BasicFramework.SoftSecurity.MD5Encrypt(origin, "spiderzj");
        }

        private void button2_Click(object sender, EventArgs e)
        {
            OpenFileDialog dialog = new OpenFileDialog();
            dialog.Multiselect = true;//该值确定是否可以选择多个文件
            dialog.Title = "请选择文件夹";
            string file = "";
            dialog.Filter = "文本文件(*.txt)|*.txt";
            if (dialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                  file = dialog.FileName;
            }
            txtpl.Text = file;
        }

        private void WriteLogFile(List<string> input)
        {
            // 利用SaveFileDialog，让用户指定文件的路径名
            SaveFileDialog saveDlg = new SaveFileDialog();
            saveDlg.Filter = "文本文件|*.txt";
            if (saveDlg.ShowDialog() == DialogResult.OK)
            {
                // 创建文件，将textBox1中的内容保存到文件中
                // saveDlg.FileName 是用户指定的文件路径
                FileStream fs = File.Open(saveDlg.FileName,
                    FileMode.Create,
                    FileAccess.Write);
                StreamWriter sw = new StreamWriter(fs);

                // 保存textBox1中所有内容（所有行）
                foreach (string line in input)
                {
                    sw.WriteLine(line+"  注册码:"+ AuthorizeEncrypted(line));
                }
                //关闭文件
                sw.Flush();
                sw.Close();
                fs.Close();
                // 提示用户:文件保存的位置和文件名
                MessageBox.Show("文件已成功保存到" + saveDlg.FileName);
            }
        }


        private void test(string sendString)
        {
            {
                bool IsExist = false;
                Process[] pros = Process.GetProcesses(); //获取本机所有进程
                for (int i = 0; i < pros.Length; i++)
                {
                    if (pros[i].ProcessName == "Print32To64") //名称为ProcessCommunication的进程
                    {
                        IsExist = true;
                        IntPtr hWnd = pros[i].MainWindowHandle; //获取ProcessCommunication.exe主窗口句柄
                        if (hWnd == IntPtr.Zero)
                            hWnd = pros[i].MainWindowHandle; //获取ProcessCommunication.exe主窗口句柄


                        byte[] sarr = System.Text.Encoding.Default.GetBytes(sendString);
                        int len = sarr.Length;

                        COPYDATASTRUCT cds;
                        cds.dwData = hWnd;
                        cds.cbData = len + 1;
                        cds.lpData = sendString;
                        int rt = SendMessage(hWnd, WM_COPYDATA, 0, ref cds);


                    }

                }
                if (!IsExist)
                {
                    string filePath = System.Environment.CurrentDirectory;

                    string agentExe = filePath + "\\Print32To64.exe";

                    var startInfo = new ProcessStartInfo(agentExe);
                    var proc = Process.Start(startInfo);
                    //int hWnd = FindWindow("Print32To64", null);
                    byte[] sarr = System.Text.Encoding.Default.GetBytes(sendString);
                    int len = sarr.Length;
                    Thread.Sleep(1000);//启动后，等待一秒再发送
                    COPYDATASTRUCT cds;
                    cds.dwData = (IntPtr)0;
                    cds.cbData = len + 1;
                    cds.lpData = sendString;
                    IntPtr hWnd = proc.MainWindowHandle; //获取ProcessCommunication.exe主窗口句柄
                    if (hWnd == IntPtr.Zero)
                        hWnd = proc.MainWindowHandle; //获取ProcessCommunication.exe主窗口句柄
                    int data = Convert.ToInt32("0"); //获取文本框数据
                    int rt = SendMessage(hWnd, WM_COPYDATA, 0, ref cds); //点击该按钮，以文本框数据为参数，向Form1发送WM_KEYDOWN消息

                }
            }
        }
    }
}
